What are pseudo-classes and pseudo-elements in CSS, and how are they used?
56
21-Oct-2024
Ashutosh Kumar Verma
21-Oct-2024Pseudo-classes are used to define special states of an element. They allow you to style elements based on user interaction (such as hovering), their position in the DOM, or their state (such as having focus). Common pseudo-classes include,
:hover
: Styles the element when the mouse pointer is over it.:focus
: Styles the element when it has focus (such as an input field).:nth-child(n)
: Styles the element based on its position in the parent (for example, every third child).Example-
Pseudo-elements are used to style a specific part of an element, such as the first letter, the first line, or to insert content before or after an element's content. Common pseudo-elements include,
::before
: Inserts content before the element's actual content.::after
: Inserts content after the element's actual content.::first-letter
: Styles the first letter of the element.::first-line
: Styles the first line of the element.Example-